import {Component, ViewChild} from "@angular/core";
import {Content, IonicPage, NavController, Refresher} from "ionic-angular";
import {StaffAddorchangePage} from "../staff-addorchange/staff-addorchange";
import {HttpClient} from "@angular/common/http";
import {AppUrl} from "../../../../app/app.general";
import {CommonService} from "../../../../app/common.service";

@IonicPage()
@Component({
  templateUrl:'staff-show.html',
  selector:'staff-show-page'
})

export class StaffShowPage{
  @ViewChild(Content) content: Content;
  @ViewChild(Refresher) refresher: Refresher;

  staffList:any[];
  flag:any;
  pageList={
    pageNo:1,
    pageSize:5,
    isLastPage:false
  }
  constructor(private navCtrl:NavController,private http:HttpClient,private commonService:CommonService){}

  ionViewWillEnter(){
    this.refresher._top = '50px';
    this.refresher.state = 'refreshing';
    this.refresher._beginRefresh();
  }

  doRefresh(){
    this.pageList = {
      isLastPage: false,
      pageSize: 5,
      pageNo: 0
    };
    this.getdata(this.refresher);
  }

  getdata(refresher?:any){
    this.pageList.pageNo++;
    if(refresher){
      this.refresher.complete();
      this.staffList=[];
    }
    this.http.post(AppUrl.user.getAllstaff,{pageNo:this.pageList.pageNo,pageSize:this.pageList.pageSize}).subscribe(data=>{
      console.log(data);
      let temp1:any=data;
      let temp=temp1.data;
      this.pageList.isLastPage = temp[0]==0?true:false;
      // this.staffList.push(temp[1]);
      for(let ar of temp[1]) {
        this.staffList.push(ar);
      }
    },reject=>{
      this.commonService.httpError(reject);
      this.refresher.complete();
    });
  }
  doInfinite(infiniteScroll):Promise<any>{
    return new Promise((resolve)=>{
      let that=this;
      setTimeout(function () {
        if(!that.pageList.isLastPage){
          that.getdata();
          resolve();
        }else{
          resolve();
        }
      },1000);
    });
  }



  viewOrchange(flag,userid){
    //flag:0-add;1-modify
    this.flag=flag;
    this.navCtrl.push('StaffAddorchangePage',{flag:flag,userid:userid,callback:this.getcallback});
  }
  getcallback=(data)=>{
    return new Promise((resolve,reject)=>{
      console.log(data);
      let temp:any=[];
      temp[0]=data;
      if(this.flag==1){
        //flag:1-modify;
        let index=this.staffList.findIndex(e=>e.userid==data.userid);
        this.staffList[index]=temp;
      }else{
        //flag:0-add;
        let temp1:any=temp.concat(this.staffList);
        console.log(temp1);
        this.staffList=temp1;
      }
      resolve();
    });
  }

}
